package alo.p3.work;

import alo.p3.ListNode;
//逐对置换链表
public class ReversePairRecursive {

    //使用递归的方法
    ListNode ReversePairRecursive1(ListNode headNode){
        ListNode temp;
        if (headNode==null)
            return null;
        else {
            temp=headNode.getNext();
            headNode.setNext(temp.getNext());
            temp.setNext(headNode);
            headNode=temp;

            headNode.getNext().setNext(ReversePairRecursive1(headNode.getNext().getNext()));
            return headNode;
        }
    }



    //使用迭代的方法
    ListNode ReversePairRecursive2(ListNode headNode){
        ListNode temp1=null,temp2=null;
        while (headNode!=null&&headNode.getNext()!=null){
            if (temp1!=null){
                //把前一对与第二对的第二位连接
                temp1.getNext().setNext(headNode.getNext());
            }
            //第一位和第二位交换
            temp1=headNode.getNext();
            headNode.setNext(temp1.getNext());
            temp1.setNext(headNode);
            //设置temp2为开始结点
            if (temp2==null)
                temp2=temp1;
            headNode=headNode.getNext();
        }
        return temp2;
    }

}
